package com.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 授权过滤器
 */
@Component
@Slf4j
public class AuthorizationFilter extends ZuulFilter {
    public String filterType() {
        return "pre";
    }

    public int filterOrder() {
        return 3;
    }

    public boolean shouldFilter() {
        return true;
    }

    public Object run() throws ZuulException {
        log.info("authorization start");
        RequestContext requestContext=RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        /**
         * 权限判断,是否需要认证
         */
        if(isNeedAuth(request)){
            TokenInfo tokenInfo = (TokenInfo) request.getAttribute("tokenInfo");

            if(tokenInfo!=null&&tokenInfo.isActive()){

                if(!hasPermission(tokenInfo,request)){
                    log.info("audit log update fail 403");
                    handleError(403,requestContext);
                }
                requestContext.addZuulRequestHeader("username",tokenInfo.getUser_name());
            }else{
                if(!StringUtils.startsWith(request.getRequestURI(),"/token")){
                    log.info("audit log update fail 401");
                    handleError(401,requestContext);
                    return null;
                }
            }
        }
        else{

        }

        return null;
    }

    /**
     * 模拟获取权限请求，50%的概率报403
     * @param tokenInfo
     * @param request
     * @return
     */
    private boolean hasPermission(TokenInfo tokenInfo, HttpServletRequest request) {
//        return RandomUtils.nextInt()%2==0;
        return true;
    }

    private void handleError(int i, RequestContext requestContext) {
        requestContext.getResponse().setContentType("application/json");
        requestContext.setResponseStatusCode(i);
        requestContext.setResponseBody("{\"message\":\"auth fail\"}");
        requestContext.setSendZuulResponse(false);
    }

    private boolean isNeedAuth(HttpServletRequest request) {
        return true;
    }
}
